#!/usr/bin/env python
# -*- coding: utf-8 -*-
from string import Template
from tack.lib import json_app, string_app, content_headers, status_codes
from tack_ocie.api.util import build_row_dict, sql_string, sql_int

get_all_sql = """
SELECT * FROM ocie_unit
WHERE active=1
ORDER BY unit_id
"""

get_keyed_sql = """
SELECT * FROM ocie_unit
WHERE unit_id = $key
"""

add_unit_sql = """
INSERT INTO ocie_unit VALUES ($description)
"""

check_for_unit_sql = """
SELECT unit_id
FROM ocie_unit
WHERE description = $description AND active = 1
"""


update_unit_sql = """
UPDATE ocie_unit
SET description = $description
WHERE unit_id = $key
"""

delete_unit_sql = """
UPDATE ocie_unit
SET active = 0
WHERE unit_id = $key
"""

def get_all(environ, start_response):
    sql = Template(get_all_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    output = []
    for row in rows:
        row_dict = build_row_dict(cursor.description, row)
        output.append(row_dict)
    return json_app(output)(environ, start_response)

def get_keyed(environ, start_response):
    key = environ['dispatcher.groups']['key']
    sql = Template(get_keyed_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if rows:
        output = []
        for row in rows:
            row_dict = build_row_dict(cursor.description, row)
            output.append(row_dict)
        output = json_dumps(output, indent=2)
    else:
        start_response(status_codes.not_found, content_headers.default_plain())
        return ['404 Not Found']
    return string_app(output)(environ, start_response)
    
def add_unit(environ, start_response):
    description = sql_string(environ['form']['description'])
    sql = Template(check_for_unit_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if len(rows):
        start_response(status_codes.conflict, content_headers.default_plain())
        return ['Unit Exists']
    sql = Template(add_unit_sql).substitute(locals())
    cursor.execute(sql)
    environ['connection'].commit()
    rows = query(environ['connection'], 'SELECT CAST(@@IDENTITY AS INT)')
    return json_app(output)(environ, start_response)
    
def update_unit(environ, start_response):
    key = environ['dispatcher.groups']['key']
    description = sql_string(environ['form']['description'])
    sql = Template(update_unit_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    environ['connection'].commit()
    output = 'Updated'
    return string_app(output)(environ, start_response)

def delete_unit(environ, start_response):
    key = environ['dispatcher.groups']['key']
    sql = Template(delete_unit_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    environ['connection'].commit()
    output = 'Deleted'
    return string_app(output)(environ, start_response)
